import { i18n } from '@/i18n'
import { useUserStore } from '@/store/modules/user.js'
import { getToken } from '@/utils/auth.js'
import { createRouter, createWebHistory } from 'vue-router'

const Layout = () => import('../layout/index.vue')
const { t } = i18n.global
const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/home',
      component: Layout,
      children: [
        {
          path: 'home',
          name: 'home',
          component: () => import('../views/home/index.vue'),
        },
      ],
    },
    {
      path: '/cart',
      name: 'Cart',
      component: Layout,
      meta: {
        requiresAuth: true,
      },
      children: [
        {
          path: '',
          name: 'CartIndex',
          component: () => import('@/views/cart/index.vue'),
        },
      ],
    },
    {
      path: '/user',
      name: 'User',
      component: Layout,
      meta: {
        requiresAuth: true,
      },
      children: [
        {
          path: '',
          name: 'UserIndex',
          component: () => import('@/views/user/index.vue'),
          redirect: '/user/info',
          children: [
            {
              path: 'info',
              name: 'userInfo',
              component: () => import('@/views/user/info.vue'),
            },
            {
              path: 'order',
              name: 'userOrder',
              component: () => import('@/views/user/order.vue'),
            },
          ],
        },
      ],
    },
  ],
})
router.beforeEach (async (to, from, next) => {
  if (to.path !== from.path) {
    const token = getToken()
    const userStore = useUserStore()
    if (token) {
      await userStore.getUserInfo()
      next()
    }
    else {
      if (to.meta.requiresAuth) {
        window.$message.error(t('message.notLoggedInMessage'))
        next('/')
      }
      else {
        next()
      }
    }
  }
  else { next() }
})

router.afterEach(() => {
})
export default router
